<template>
  <div :class="containerClass">
    <div class="bg-gray-100 rounded-3xl px-4 py-3 mx-4 border border-gray-200 flex flex-col">
      <!-- 文本输入框 -->
      <textarea
        placeholder="给小满AI机器人发送消息"
        class="bg-transparent border-none outline-none w-full text-sm resize-none min-h-[24px]"
        rows="2"
        ref="textareaRef"
        v-model="userMessage"
        @input="autoResize"
        @keydown.enter="handleEnter"
      ></textarea>

      <!-- 模型选择 联网搜索 -->
      <div class="flex mt-3">
        <div class="flex gap-2 relative" ref="leftContainerRef">
          <!-- 模型选择 -->
          <div
            class="border border-gray-300 px-2 py-1 rounded-3xl flex items-center justify-center hover:bg-gray-200 cursor-pointer"
            @click="toggleModelDropdown"
            ref="selectRef"
          >
            <SvgIcon :name="currentModel.icon" customSvgCss="w-5 h-5 me-1.5" />
            <span class="text-gray-800 text-xs">{{ currentModel.name }}</span>
            <SvgIcon
              name="down-arrow"
              customSvgCss="w-5 h-5 ml-1 text-gray-800 transform transition-transform duration-300"
              :class="isModelDropdownOpen ? 'rotate-180' : ''"
            />
          </div>
          <!-- 模型选择下拉框 -->
          <div
            v-if="isModelDropdownOpen"
            ref="dropdownRef"
            :class="[
              'absolute',
              'left-0',
              'w-48',
              'bg-white',
              'rounded-lg',
              'shadow-lg',
              'border',
              'border-gray-200',
              'z-10',
              'overflow-hidden',
              dropdownPosition,
            ]"
          >
            <div
              v-for="model in models"
              :key="model.id"
              class="px-3 py-2 hover:bg-gray-100 cursor-pointer flex items-center justify-between"
              @click="selectModel(model)"
            >
              <div class="flex items-center">
                <SvgIcon :name="model.icon" customSvgCss="w-5 h-5 mr-2" />
                <div class="flex flex-col text-xs">
                  <p class="text-gray-800">{{ model.name }}</p>
                  <p class="text-gray-500">{{ model.description }}</p>
                </div>
              </div>
              <!-- 选中图标 -->
              <SvgIcon v-if="model.selected" name="check" customSvgCss="w-3 h-3 text-gray-600" />
            </div>
          </div>
          <!-- 联网搜索 -->
          <div
            class="ml-3 border px-2 py-1 rounded-3xl flex items-center justify-center cursor-pointer"
            :class="
              isNetwork
                ? 'border-[#ceddee] bg-[#DBEAFE] hover:bg-[#c3daf8]'
                : 'border-gray-300 hover:bg-gray-200'
            "
            @click="toggleNetwork"
          >
            <SvgIcon
              name="network"
              customSvgCss="w-5 h-5 mr-1.5"
              :class="isNetwork ? 'text-[#4d6bfe]' : 'text-gray-500'"
            />
            <span class="text-xs mr-1" :class="isNetwork ? 'text-[#4d6bfe]' : 'text-gray-800'"
              >联网搜索</span
            >
          </div>
        </div>
        <div class="grow"></div>

        <!-- 发送按钮 -->
        <div class="flex justify-end mt-3">
          <a-tooltip placement="top">
            <template #title><span>请输入你的问题</span></template>
            <button
              class="flex items-center justify-center bg-[#4d6bfe] rounded-full w-8 h-8 border border-[#4d6bfe] hover:bg-[#3b5bef] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              @click="handleSendMessage"
              :disabled="!userMessage.trim()"
            >
              <SvgIcon name="up-arrow" customSvgCss="w-5 h-5 text-white" />
            </button>
          </a-tooltip>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import SvgIcon from './SvgIcon.vue'
import { message } from 'ant-design-vue'
import { useChatStore } from '@/stores/chatStore'

const selectRef = ref(null)
const textareaRef = ref(null)
const isModelDropdownOpen = ref(false)
const leftContainerRef = ref(null)
const dropdownRef = ref(null)
// 下拉菜单位置
const dropdownPosition = ref('top-8')

const chatStore = useChatStore()

const models = computed(() => chatStore.models)
const isNetwork = computed(() => chatStore.isNetWork)
const currentModel = computed(() => chatStore.selectedModel)

// 接收父组件传递的属性
const props = defineProps({
  // textarea中用户输入的用户消息
  modelValue: {
    type: String,
    required: true,
  },
  containerClass: {
    type: String,
    default: '',
  },
})

// textarea自适应高度
const autoResize = () => {
  const textarea = textareaRef.value
  if (textarea) {
    textarea.style.height = 'auto' // 重置高度

    const newHeight = Math.min(textarea.scrollHeight, 150) // 最大高度300px
    textarea.style.height = newHeight + `px` // 设置为内容的高度

    // 超过最大高度时显示滚动条
    textarea.style.overflowY = textarea.scrollHeight > 150 ? 'auto' : 'hidden'
  }
}

const emit = defineEmits(['update:modelValue', 'sendMessage'])

const userMessage = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  },
})

// 发送消息
const handleSendMessage = () => {
  if (!userMessage.value.trim()) {
    message.warning('消息不能为空')
    return
  }

  emit('sendMessage', {
    selectedModel: chatStore.selectedModel,
    isNetWork: chatStore.isNetWork,
  })

  // 清空输入框
  userMessage.value = ''
}

// 下拉菜单显示/隐藏
const toggleModelDropdown = () => {
  isModelDropdownOpen.value = !isModelDropdownOpen.value

  if (isModelDropdownOpen.value) {
    nextTick(() => {
      if (leftContainerRef.value && dropdownRef.value) {
        // 返回元素相对于视图窗口的位置和尺寸信息
        const btnRect = leftContainerRef.value.getBoundingClientRect()
        // 下拉菜单的实际高度
        const dropHeight = dropdownRef.value.offsetHeight

        if (window.innerHeight - btnRect.bottom < dropHeight) {
          dropdownPosition.value = 'bottom-10'
        } else {
          dropdownPosition.value = 'top-8'
        }
      }
    })
  }
}

// 点击外部区域关闭下拉菜单
const handleClickOutside = (e) => {
  if (selectRef.value && !selectRef.value.contains(e.target)) {
    isModelDropdownOpen.value = false
  }
}

// 回车键
const handleEnter = () => {
  handleSendMessage()
}

// 挂载时添加监听事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 卸载时移除监听事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

const selectModel = (model) => {
  console.log('切换Model: ', model)
  chatStore.updateSelectedModel(model)

  isModelDropdownOpen.value = false
}

const toggleNetwork = () => {
  chatStore.updateNetStatus(!chatStore.isNetWork)
}
</script>
